package com.training.utils;

import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class KeyStoreManager {
    private static final String KEY_ALIAS = "training_app_key";
    private static final String ANDROID_KEYSTORE = "AndroidKeyStore";

    /**
     * 检查密钥对是否存在
     *
     * @return true表示存在，false表示不存在
     * @throws Exception
     */
    public static boolean isKeyPairExists() throws Exception {
        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
        keyStore.load(null);

        // 同时检查证书和私钥是否存在
        boolean aliasExists = keyStore.containsAlias(KEY_ALIAS);
        boolean certificateExists = keyStore.getCertificate(KEY_ALIAS) != null;
        boolean keyExists = keyStore.getKey(KEY_ALIAS, null) != null;

        return aliasExists && certificateExists && keyExists;
    }

    /**
     * 生成RSA密钥对
     *
     * @param context
     * @throws Exception
     */
    public static void generateRSAKeyPair(Context context) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEYSTORE);

        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
                KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setKeySize(2048);

        keyPairGenerator.initialize(builder.build());
        keyPairGenerator.generateKeyPair();
    }

    /**
     * 如果密钥对不存在，则生成新的RSA密钥对
     *
     * @param context
     * @throws Exception
     */
    public static void generateRSAKeyPairIfNotExists(Context context) throws Exception {
        if (!isKeyPairExists()) {
            generateRSAKeyPair(context);
        }

    }

    public static PublicKey getPublicKey() throws Exception {
        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
        keyStore.load(null);
        Certificate certificate = keyStore.getCertificate(KEY_ALIAS);
        if (certificate == null) {
            return null;
        }
        return certificate.getPublicKey();
    }

    public static PrivateKey getPrivateKey() throws Exception {
        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
        keyStore.load(null);
        return (PrivateKey) keyStore.getKey(KEY_ALIAS, null);
    }
}